from . import index_blu
from flask import render_template, request, session, redirect, url_for
from models import db
from models.user import User


@index_blu.route("/")
def index():
    # return "我是index视图函数"
    # return render_template("profile.html")
    # 如果提取到user_id那么就说明用户之前已经登录，否则未登录
    user_id = session.get("user_id")
    if not user_id:
        return redirect(url_for("index.login"))

    # 根据从session中提取到的id，查询数据库
    user = db.session.query(User).filter(User.user_id == user_id).first()

    return render_template("profile.html", user=user)


@index_blu.route("/login", methods=['GET', 'POST'])
def login():
    if request.method == "POST":
        user_name = request.form.get("Username")
        user_password = request.form.get("Password")
        print("password", user_password)
        user = db.session.query(User).filter(User.user_name == user_name, User.user_password == user_password).first()
        if user:
            # 使用session的方式进行状态保持
            session['user_id'] = user.user_id
            # return "登录成功"
            return redirect(url_for("index.index"))
        else:
            return "登录失败..."
    else:
        return render_template("login.html")


@index_blu.route("/logout")
def logout():
    session.clear()
    return redirect(url_for("index.login"))


@index_blu.route("/register")
def register():
    return render_template("register.html")
